<?php
/*
# ------------------------------------------------------------------------
# JA Job Board component for Joomla 1.5
# ------------------------------------------------------------------------
# Copyright (C) 2004-2009 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
# @license - Copyrighted Commercial Software
# Author: J.O.O.M Solutions Co., Ltd
# Websites:  http://www.joomlart.com -  http://www.joomlancers.com
# This file may not be redistributed in whole or significant part.
# ------------------------------------------------------------------------
*/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );


/**
 * @package		Joomla
 * @subpackage	JobBoard
 */
class JobBoardTableJA_Jobs extends JTable
{
    
    /** @var int Primary key */
    var $id             = null;
	var $direct_url = null;
	/**
	* @param database A database connector object
	*/
	function __construct(&$db)
	{
		global $mainframe, $option;
        
        $table_name        = $mainframe->getUserStateFromRequest( $option .".jamanageforms.table_name",   'table_name',        'ja_jobs',    'cmd' );
        parent::__construct( "#__$table_name", 'id', $db );

        // Get other field
        $query = 
            "SELECT id, field_name, field_type, field_width, field_height "
            ." FROM  #__ja_form_fields "
            ." WHERE table_name = '". $table_name ."' AND field_name!='' AND (field_state = 'chg' OR field_state = 'add') AND published=1"
            ." ORDER BY field_ordering";
       $this->_db->setQuery($query);
       $fields = $this->_db->loadObjectList();
		
       $count = 0;
       $count_editor = 0;
       $arr_temp_editor = array();
       $arr_temp = array();
       for($i = 0, $n = count($fields); $i < $n; $i++){
           $field_name = $fields[$i]->field_name; 
           $this->$field_name = null;
           
           
           if (($fields[$i]->field_type=='IMAGE')||($fields[$i]->field_type=='FILE')||($fields[$i]->field_type=='DATE_CAL'))
           {
	           	$arr_temp[$count]['name'] = $fields[$i]->field_name;
	           	$arr_temp[$count]['type'] = $fields[$i]->field_type;
	           	$arr_temp[$count]['field_width'] = $fields[$i]->field_width;
	           	$arr_temp[$count]['field_height'] = $fields[$i]->field_height;
	           	$count=$count + 1; 
           }          
           if (($fields[$i]->field_type=='EDITOR'))
           {
	           	$arr_temp_editor[$count_editor] = $fields[$i]->field_name;
	           	$count_editor += 1;
           }
       }
       $this->editor_field = $arr_temp_editor;
       $this->spec_field = $arr_temp;
	}
	
	/**
	 * Overloaded check function
	 *
	 * @access public
	 * @return boolean
	 * @see JTable::check
	 * @since 1.5
	 */
	function check()
	{ 
		global $jbconfig, $mainframe;
		
		$filter	= new JFilterInput( '', '', 1, 1);
//		JFilterOutput::objectHTMLSafe($this,ENT_QUOTES,'');
		$cid = $this->id;
		$where_more = '';
		$user = JFactory::getUser();
		if($cid){			
			if(in_array($user->usertype,array('Administrator','Super Administrator'))){
				$where_more = " and (display in ('show_all', 'hide_on_view', 'hide_on_new', 'admin_only', 'hide_on_edit'))";
			}
			else $where_more = " and ( display in ('show_all', 'hide_on_view' ) ) ";
		}
		else{
			if(in_array($user->usertype,array('Administrator','Super Administrator'))){
				$where_more = " and (display in ('show_all', 'hide_on_view', 'hide_on_new', 'admin_only', 'hide_on_edit'))";
			}
			else $where_more = " and display in ('show_all', 'hide_on_view', 'hide_on_edit')";
		}
		$warning_msg =JText::_("There are some invalid data. Please check again.");
        $fieldList = getEditFieldList('ja_jobs', $where_more);
        for($i = 0, $n = count($fieldList); $i < $n; $i++){
        	
            $field = $fieldList[$i];
            $this->{$field->field_name} = preg_replace('@<script[^>]*?.*?</script>@siu','',$this->{$field->field_name});
            $this->{$field->field_name} = $filter->clean($this->{$field->field_name});
            $this->{$field->field_name} = ltrim($this->{$field->field_name});
			$this->{$field->field_name} = rtrim($this->{$field->field_name});
			
            if($field->is_required){
				if(is_null($this->{$field->field_name}) || $this->{$field->field_name} == "")
                {
                	if (!$field->error_message)
                		JError::raiseWarning(0,$warning_msg);
                	else
                		JError::raiseWarning(1, JText::_($field->error_message) );
                    return false;
                }
            } 
			
			
            switch($field->field_validate_type){
                case "number":
                	if($this->{$field->field_name}!='')
                    	if(!is_numeric($this->{$field->field_name})){
                    		if (!$field->error_message)
                    			JError::raiseWarning(0,$warning_msg);
                    		else
	                    		JError::raiseWarning(1, JText::_($field->error_message) );
	                        return false;
                    }
					break;
                case "email":
                	if($this->{$field->field_name}!='')
						if(!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $this->{$field->field_name})&&!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{3,4})$/i', $this->{$field->field_name})&&!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{4,5})$/i', $this->{$field->field_name})){
							if (!$field->error_message)
								JError::raiseWarning(0,$warning_msg);
							else 
                        		JError::raiseWarning(1, JText::_($field->error_message) );
                        	return false;
                    }
                    break;
                /*case "date":
                	if($this->{$field->field_name}!=''){
                		
                		if ( ! $mainframe->isAdmin () ) {
                			$format = $jbconfig['general']->get("format_date", "%Y-%m-%d");
                        	$this->{$field->field_name} = $this->convertTime("Y-m-d", $format, $this->{$field->field_name});  
                		}
	                    if(!preg_match('/^[0-9]{4}([-\/][0-9]{2}){2}$/i', $this->{$field->field_name})){
	                    	if (!$field->error_message)
	                    		JError::raiseWarning(0,$warning_msg);
	                    	else
                        		JError::raiseWarning(1, JText::_($field->error_message));
                        	return false;
	                    }
                	}
                    break;*/
                case "time":
                	if($this->{$field->field_name}!='')
                    	if(!preg_match('/^[0-9]{2}(:[0-9]{2}){2}$/i', $this->{$field->field_name})){
                    		if (!$field->error_message)
                    			JError::raiseWarning(0,$warning_msg);
                    		else 
                       			JError::raiseWarning(1, JText::_($field->error_message));
                        	return false;
                    }
                    break;
                case "date":				
				case "datetime":
                    if(  $this->{$field->field_name} !='' && ($field->field_type == "DATE" || $field->field_type == "DATE_CAL") ) {
                    	$format = $jbconfig['general']->get("format_date", "%Y-%m-%d");
                    	
                    	if( $field->field_validate_type == "date" && strpos($format, " ") !== false){
                    		$format = explode(" ", $format);
                    		$format = $format[0];
                    		if( strpos($this->{$field->field_name}, " ") !== false ){
                    			$arrTemp = explode(" ", $this->{$field->field_name});
                    			$this->{$field->field_name} = $arrTemp[0];
                    		}
                    	}
                    	
                    	// Build regular expression
                    	$reg = str_replace("%", "", $format);
                    	$reg = str_replace(array("/", ".", "-"), "-", $reg);
                    	$reg = str_replace(" ", "[ ]+", $reg);
                    	$reg = str_replace("-", "[-\/.]", $reg);
                    	$reg = str_replace("Y", "[0-9]{4}", $reg);                    	
                    	$reg = str_replace("m", "[0-9]{2}", $reg);
                    	$reg = str_replace("d", "[0-9]{2}", $reg);                    	
                    	$reg = str_replace("H", "[0-9]{2}", $reg);
                    	$reg = str_replace(":i", "(:[0-9]{2})", $reg);
                    	$reg = str_replace(":s", "(:[0-9]{2})", $reg);
                    	$reg = "/^".$reg."$/i";
                    	
                    	if (!preg_match($reg, $this->{$field->field_name})){   
                    		$this->{$field->field_name} = "";                    		              		
                    		if (!$field->error_message)
                    			JError::raiseWarning(0,$warning_msg);
                    		else 
                        		JError::raiseWarning(1, JText::_($field->error_message));
                        	return false;
	                    }
						
	                    // Build format standart to insert data.
	                    $this->{$field->field_name} = $this->convertTime("Y-m-d H:i:s", $format, $this->{$field->field_name});
                    	JRequest::setVar($field->field_name, $this->{$field->field_name});
                    }
					break;
				default:
					break;
            }
        }
        
        $config = new JConfig();
        
        $employerOffset = 0;
        $employerDetails = getProfileFromUserId($this->user_id);
        if( ! empty($employerDetails->time_offset) ){
        	$employerOffset = intval( $employerDetails->time_offset*60*60);
        }
        
        $this->effected_date = date('Y-m-d H:i:s', strtotime($this->effected_date)+ date('Z')- $user->getParam('timezone', $config->offset)*60*60 + $employerOffset);
        
        if ( $mainframe->isAdmin () )
        	$this->created_date = date('Y-m-d H:i:s', strtotime($this->created_date)+ date('Z')- $user->getParam('timezone', $config->offset)*60*60 + $employerOffset);
        
        // Expire date
        if( ! empty($this->expiry_date) ){            
            $this->expiry_date = date('Y-m-d H:i:s', strtotime($this->expiry_date)+ date('Z')- $user->getParam('timezone', $config->offset)*60*60 + $employerOffset);            
        }else{
            global $jbconfig;      
            
            if( JRequest::getVar('is_hotjob', "0") != "1" )
                $duration_standard_post = $jbconfig ['posts']->get ( 'posts_display_days', 30 );
            else 
                $duration_standard_post = $jbconfig ['posts']->get ( 'posts_show_days_elapsed', 30 );
	        
            // $this->expiry_date = date('Y-m-d H:i:s', strtotime( $this->effected_date ) + $duration_standard_post*24*60*60  + $employerOffset );            
        }	
        	
        return true;
	}
	
	function convertTime($outputFormat, $inputFormat, $strings) {
		$inputFormat = str_replace(array("%", "/", " ", ":"), array("", "-", "-", "-"), $inputFormat);
		$inputFormat = explode("-", $inputFormat);
		
		$string = str_replace(array("%", "/", " ", ":", "."), array("", "-", "-", "-"), $strings);
		$string = explode("-", $string); 
		
		$arr = array();
		$arr['H'] = 0;
		$arr['i'] = 0;
		$arr['s'] = 0;
		$arr['m'] = 0;
		$arr['d'] = 0;
		$arr['Y'] = 0;
		if ( count($inputFormat) == count($string) || ( count($inputFormat) == 2*count($string)) || ( 2*count($inputFormat) == count($string) ) ) {
			foreach ($inputFormat as $key => $input){
				$arr[$input] = $string[$key];
			}
		}
		if($arr['H'] <0 || $arr['H'] > 12)
			return $strings;
		if($arr['i'] <0 || $arr['i'] > 60)
			return $strings;
		if($arr['s'] <0 || $arr['s'] > 60)
			return $strings;
		if($arr['m'] <0 || $arr['m'] > 12)
			return $strings;
		if($arr['d'] <0 || $arr['d'] > 31)
			return $strings;
		if($arr['Y'] <0 || $arr['Y'] > 3000)
			return $strings;
		return date($outputFormat, mktime( $arr['H'], $arr['i'], $arr['s'], $arr['m'], $arr['d'], $arr['Y'] ));
	}
	
	function load($key)
	{
		parent::load($key);
		$user = JFactory::getUser();
		$employerOffset = 0;
        $employerDetails = getProfileFromUserId($this->user_id);
        if( ! empty($employerDetails->time_offset) ){
        	$employerOffset = intval( $employerDetails->time_offset*60*60);
        }
		if ($this->effected_date)
		{
			if ($user)
				$this->effected_date = date('Y-m-d H:i:s',strtotime($this->effected_date) - date('Z') + $user->getParam('timezone')*60*60 + $employerOffset);
			else 
				$this->effected_date = $this->effected_date;
		}
		if ($this->created_date)
		{
			if ($user)
				$this->created_date = date('Y-m-d H:i:s',strtotime($this->created_date) - date('Z') + $user->getParam('timezone')*60*60 + $employerOffset);
			else 
				$this->created_date = $this->created_date;
		}
		
		if (isset($this->expiry_date))
		{
			if ($user)
				$this->expiry_date = date('Y-m-d H:i:s',strtotime($this->expiry_date) - date('Z') + $user->getParam('timezone')*60*60 + $employerOffset);
			else 
				$this->expiry_date = $this->expiry_date;
		}
		return $this;
	}
}